const cheerio = require('cheerio')
const http = require('../request/request')
const {getHtmlDeatil} = require('../util/getHtml')
const pretty = require('pretty')
const {Base64} = require('js-base64')
const  getItemMovieInfo = require('../util/getItemMovieInfo')

// 格式化当前剧集链接
function formatEpisode(str) {
    // console.log('strr',str)
    // console.log(str.split('https'))
    let result = []
    // 说明只有单个剧集
    if (str.split('https').length == 2) {
       let playPath = 'https' + decodeURIComponent(str.split('https')[1])
        result.push(playPath)
        return result
    }
    str.split('https').forEach((item,index) => {
        item = ('https' + item)
        item = item.slice(0,item.indexOf('.m3u8') + 5)
        // console.log('ssss',decodeURIComponent(item))
        let link = decodeURIComponent(item)
        if (link.includes('.m3u8')) {
            result.push(link)
        }
    })
    // result.splice(0,1) // 删除掉第一项 无用链接
    return result
}



/**
 * @name parserHtml
*/

function parserHtml ($){
    let result = {}
    let mac_url = $('.main').find('script').first().text().split(',')[$('.main').find('script').first().text().split(',').length -1]
    let start = mac_url.indexOf("'")
    let end = mac_url.lastIndexOf("'")
    let _path = mac_url.slice(start + 1 , end) // 剪切之后得到加密的m3u8地址
    let formatStr = (Base64.decode( _path).slice(Base64.decode(_path).indexOf('http')))
    result['playPath'] = formatEpisode(formatStr)
    // console.log('_path',_path);
    let done = [] // 分组切割
    $('.videourl').each((idx,item)=>{
        let obj = {
            done:0,
            title: ''
        }
        obj.title = $($('.playfrom').find('li')[idx]).text()
        obj.done = $(item).find('li').length
        done.push(obj)
    })
    result['done'] = done
    // console.log('done',done)
    let spliceStart = 0
    result.done.forEach((item,index) =>{
        item['playList'] = result.playPath.slice(spliceStart,item.done)
        spliceStart += done
    })

    return result
}

function  getGuesslist ($){
    let result = []
    $('.index-area').find('ul').find('li').each((idx,item)=>{
        result.push(getItemMovieInfo($,item))
    })
    // console.log('result',result)
    return result
}


exports.playRouter = async function (req,res){
    let query = req.query
    res.set('Cache-Control','max-age=86400')
    console.log('path',query)
    let _requestPath = query.path + '?m=' + query.m
    try {
        let {data:_html} = await getHtmlDeatil(_requestPath)
        // console.log('data_html',pretty(_html));
        let $ = cheerio.load(_html)
        let result = parserHtml($)
        let list = getGuesslist($) // 猜你喜欢
        let guessLike = {title:'猜你喜欢',list}
        res.send({
            code:200,
            msg:'获取播放地址成功',
            data:{
                result,
                guessLike
            }
        })
    }catch (err){
        console.log(err);
        res.send({
            code:100,
            msg:err || '获取失败'
        })
    }
}
